package com.jie.mongodb.service.impl;

import com.jie.mongodb.entity.SportTrack;
import com.jie.mongodb.service.RecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class RecordServiceImpl {
    @Autowired
    private RecordRepository recordRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    // 获取按时间戳升序排序的记录
    public List<SportTrack> getTracksByTrackIdAndUserIdSortedByTimeAsc(Integer trackId, Integer userId) {
        return recordRepository.findByTrackIdAndUserIdOrderByRecordTimeAsc(trackId, userId);
    }

    // 获取按时间戳降序排序的记录
    public List<SportTrack> getTracksByTrackIdAndUserIdSortedByTimeDesc(Integer trackId, Integer userId) {
        return recordRepository.findByTrackIdAndUserIdOrderByRecordTimeDesc(trackId, userId);
    }

    // 获取最老的一条数据
    public SportTrack getOldestTrackByTrackIdAndUserId(Integer trackId, Integer userId) {
        return recordRepository.findTopByTrackIdAndUserIdOrderByRecordTimeAsc(trackId, userId);
    }
    // 获取最新的一条数据
    public SportTrack getLatestTrackByTrackIdAndUserId(Integer trackId, Integer userId) {
        return recordRepository.findTopByTrackIdAndUserIdOrderByRecordTimeDesc(trackId, userId);
    }

    /**
     *  获取指定trackId和userId的记录，并按照记录的时间戳进行升序排序
     * @param trackId
     * @param userId
     * @param pageable
     * @return
     */
    public Page<SportTrack> getTracksByTrackIdAndUserIdOrderByRecordTimeAscWithPaging(Integer trackId, Integer userId, Pageable pageable) {
        Page<SportTrack> page = recordRepository.findByTrackIdAndUserIdOrderByRecordTimeAsc(trackId, userId, pageable);
        if (page == null || page.isEmpty()) {
            // 处理为空的情况，例如返回一个空的 Page 对象或者采取其他适当的措施
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
        return page;
    }

    /**
     *  获取指定trackId和userId的记录，并按照记录的时间戳进行降序排序
     * @param trackId
     * @param userId
     * @param pageable
     * @return
     */

    public Page<SportTrack> getTracksByTrackIdAndUserIdOrderByRecordTimeDescWithPaging(Integer trackId, Integer userId, Pageable pageable) {
        Page<SportTrack> page = recordRepository.findByTrackIdAndUserIdOrderByRecordTimeDesc(trackId, userId, pageable);
        if (page == null || page.isEmpty()) {
            // 类似地处理为空的情况
            return new PageImpl<>(new ArrayList<>(), pageable, 0);
        }
        return page;
    }

    /**
     * 根据特定的trackId来查询每个username都不同的用户的最新一条记录 做更新mysql的操作 经纬度要获取最后一条。
     * @param trackId
     * @return
     */
    public List<SportTrack> getLatestRecordsByTrackIdAndUserIdGroupedByUsername(Integer trackId) {
        Aggregation agg = Aggregation.newAggregation(
                // 筛选符合条件的记录
                Aggregation.match(Criteria.where("trackId").is(trackId)),
                Aggregation.sort(org.springframework.data.domain.Sort.Direction.DESC, "recordTime"),
                // 按 username 分组并获取每组最新的记录
                Aggregation.group("username")
                        .first("trackId").as("trackId")
                        .first("longitudeAndLatitudeList").as("longitudeAndLatitudeList")
                        .first("userId").as("userId")
                        .first("recordTime").as("recordTime")
                        .first("totalDistance").as("totalDistance")
                        .first("totalTime").as("totalTime")
        );
        AggregationResults<SportTrack> historys = mongoTemplate.aggregate(agg,"sport_track", SportTrack.class);
        return historys.getMappedResults();
    }
}